<template>
  <div ref="container" style="padding-bottom: 18vw;">
    <div v-if="!isError && !isSubmited && question.length !== 0" class="bottomTool" style="display: flex;align-items: center;flex-wrap: nowrap;justify-content: space-around;">
      <van-button v-if="!isNew" type="primary" block round color="#f66e71" style="margin-top:0;width: 24vw;" @click="delRecord">
        删除假条
      </van-button>
      <van-button v-if="!isNew" type="primary" block round color="#5D5DEF" style="margin-top:0;width: 24vw;" @click="submit">
        修改假条
      </van-button>
      <van-button v-if="isNew" type="primary" block round color="#5D5DEF" style="margin-top:0;" @click="submit">
        请假
      </van-button>
    </div>
    <h2 v-if="!isSubmited && question.length > 0" class="van-block__title">
      {{ title }}
    </h2>
    <div v-if="!isError && !isSubmited" style="padding-bottom:30px">
      <template v-for="(item, index) in question">
        <!-- 1文本输入 2下拉单选 3日期选择 4时间选择 5时长选择 6体温选择（统计） 7图片附件 8下拉单选（统计筛选） -->
        <van-field v-if="item.model_type !== 1 && item.model_type !== 7 && item.model_type !== 4 && item.model_type !== 10 && item.model_type !== 3 && item.model_type !== 9 && item.parent == ''" :key="'t' + index" v-model="item.answer" :name="item.id.toString()" :label="item.title" input-align="right" readonly :placeholder="item.tip" :class="{ 'required': item.is_required }" is-link @input="(item.model_type == 2 || item.model_type == 8) && handleChange" @click="showPop(item)">
          <template v-if="item.model_type == 5 || item.model_type == 6" #button>
            {{ item.model_type == 5 ? '小时' : '℃' }}
          </template>
        </van-field>
        <!-- 多选 -->
        <van-field v-if="item.model_type == 9 && item.parent == ''" :key="'t' + index" :name="item.id.toString()" :label="item.title" input-align="right" :placeholder="item.tip" readonly :class="{ 'required': item.is_required }">
          <template #input>
            <van-checkbox-group v-model="item.answer" direction="horizontal" @change="dealCheckbox($event,item)">
              <van-checkbox v-for=" (it, index) in item.option_json" :key="index" :name="it.name" shape="square">
                {{ it.name }}
              </van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>
        <!-- //时间选择 -->
        <van-field v-if="item.model_type == 4 && item.parent == ''" :ref="item.ref" :key="'t' + index" v-model="item.answer" :name="item.id.toString()" :label="item.title" input-align="right" :placeholder="item.tip" readonly :class="{ 'required': item.is_required }" is-link @click="item.optionShow = true">
        </van-field>
        <!-- //文本 -->
        <van-field v-if="item.model_type == 1 && item.parent == ''" :key="'text' + index" v-model="item.answer" :label="item.title" :placeholder="item.tip" rows="2" autosize type="textarea" maxlength="50" show-word-limit :class="{ 'required': item.is_required }" @input="checkString(item.answer, item)">
        </van-field>
        <!-- //正数 -->
        <van-field v-if="item.model_type == 10 && item.parent == ''" :key="'text' + index" v-model="item.answer" :label="item.title" :placeholder="item.tip" rows="2" autosize type="text" input-align="right"	maxlength="20" :class="{ 'required': item.is_required }" @input="checkNumber(item.answer, item)">
          <template #button>
            小时
          </template>
        </van-field>
        <!-- 图片 -->
        <van-field v-if="item.model_type == 7 && item.parent == ''" :key="'img' + index" :name="item.id.toString()" :label="item.title" :placeholder="item.tip" :class="{ 'required': item.is_required }">
          <template #input>
            <van-uploader v-model="item.pic" multiple :max-count="9">
              <div v-show="item.pic.length < 9" class="van-uploader__upload1" @click="wxCImg(item)">
                <i class="van-badge__wrapper van-icon van-icon-photograph van-uploader__upload-icon"></i>
              </div>
            </van-uploader>
          </template>
        </van-field>
        <!-- 日期 -->
        <van-field v-if="item.model_type == 3 && item.parent == ''" :key="'txt' + index" v-model="item.answer" readonly clickable input-align="right" :label="item.title" :class="{ 'required': item.is_required }" :placeholder="item.tip" @click="item.optionShow = true"></van-field>
        <van-calendar v-if="item.model_type == 3" :key="item.id + 'text'" v-model="item.optionShow" :min-date="minDate" :max-date="maxDate" :default-date="new Date(item.answer || defaultDate)" color="#5d5def" @confirm="onConfirmOption($event, item)"></van-calendar>
        <!-- 其他 -->
        <van-popup v-if="item.model_type !== 3" :key="item.id" v-model="item.optionShow" round position="bottom">
          <van-picker v-if="item.model_type == 2 || item.model_type == 5 || item.model_type == 6 || item.model_type == 8" :title="'选择' + item.title" show-toolbar :columns="item.columns" :default-index="item.default" @cancel="item.optionShow = false" @confirm="onConfirmOption($event, item)"></van-picker>
          <van-datetime-picker v-if="item.model_type == 4" type="time" title="选择时间" :min-hour="0" :max-hour="23" :value="item.answer" @confirm="onConfirmOption($event, item)" @cancel="item.optionShow = false">
          </van-datetime-picker>
        </van-popup>
      </template>
      <van-empty v-if="question.length == 0" :description="studentInfo.studentName + '(' + studentInfo.attnDate + ')' + '无请假记录！'">
      </van-empty>
    </div>

    <!-- 用餐信息 -->
    <van-popup v-model="diningInfoDialog" round position="bottom">
      <div class="setDiningTitle">
        请假信息如下
      </div>
      <div style="height: 460px;overflow: scroll;">
        <div v-if="!cansEditRole" class="confirmInfo">
          <div v-if="delFlag" class="red" style="color: #f71717;
    padding: 14px 16px 0;
    font-size: 14px;
    border-top: 1px #e7e7e7 solid;"
          >
            删除假条后用餐状态将退回至初始状态，如下：
          </div>
          <template v-for="(item) in saveDiningData">
            <!-- <van-field v-if="item.breakfast" name="radio" :label="item.chineseLabel" input-align="right"> -->
            <!-- {{item.chineseLabel}} -->
            <van-cell center>
              <template #title>
                <h2 class="diningTitle">
                  <span class="date">{{ item.chineseLabel + ' ' }}</span> <span class="status">{{ creatTipText(item.mealDate) }}</span>
                </h2>
              </template>
              <!-- 使用 right-icon 插槽来自定义右侧图标 -->
              <template #label style="flex-direction: column;">
                <div v-if="item.diningId" class="diningWrap">
                  <span v-if="item.breakfast" class="diningTag">
                    {{ item.breakfast.label }}:<span :class="{ 'red': item.breakfast.value < 0, 'green': item.breakfast.value > 0 }"> {{ delFlag?'用餐':(item.breakfast.value > 0 ? '用餐' : '不用餐') }}</span>
                  </span>
                  <span v-if="item.mSnack" class="diningTag">
                    {{ item.mSnack.label }}:<span :class="{ 'red': item.mSnack.value < 0, 'green': item.mSnack.value > 0 }">
                      {{ delFlag?'用餐':(item.mSnack.value > 0 ? '用餐' : '不用餐') }}</span>
                  </span>
                  <span v-if="item.lunch" class="diningTag">
                    {{ item.lunch.label }}:<span :class="{ 'red': item.lunch.value < 0, 'green': item.lunch.value > 0 }"> {{ delFlag?'用餐':(item.lunch.value > 0 ? '用餐' : '不用餐') }}</span>
                  </span>

                  <span v-if="item.aSnack" class="diningTag">
                    {{ item.aSnack.label }}:<span :class="{ 'red': item.aSnack.value < 0, 'green': item.aSnack.value > 0 }">
                      {{ delFlag?'用餐':(item.aSnack.value > 0 ? '用餐' : '不用餐' ) }}</span>
                  </span>
                  <span v-if="item.dinner" class="diningTag">
                    {{ item.dinner.label }}: <span :class="{ 'red': item.dinner.value < 0, 'green': item.dinner.value > 0 }">
                      {{ delFlag?'用餐':(item.dinner.value > 0 ? '用餐' : '不用餐') }}</span>
                  </span>
                </div>
                <div v-if="!item.diningId" class="noData">
                  无用餐信息
                </div>
              </template>
              <template #value></template>
            </van-cell>
          </template>
        </div>

        <div v-if="saveDiningData.length > 0 && attendance == 1 && cansEditRole" style="padding-bottom: 10vw;" color="#34c8ab" animated>
          <template v-for="(item) in saveDiningData">
            <!-- v-if="item.dinner || item.aSnack || item.lunch || item.mSnack || item.breakfast" -->
            <h2 class="diningTitle">
              <span class="date">{{ item.chineseLabel + ' ' }}</span> <span class="status">{{ creatTipText(item.mealDate) }}</span>
            </h2>
            <div v-if="item.diningId" class="diningWrap">
              <van-field v-if="item.breakfast" name="radio" :label="item.breakfast.label" input-align="right">
                <template #input>
                  <van-radio-group v-model="item.breakfast.value" direction="horizontal">
                    <div v-for="(it, index) in item.breakfast.option" :key="'ba' + index">
                      <van-radio :name="it.value" checked-color="#5d5def">
                        {{ it.label }}
                      </van-radio>
                    </div>
                  </van-radio-group>
                </template>
              </van-field>
              <van-field v-if="item.mSnack" name="radio" :label="item.mSnack.label" input-align="right">
                <template #input>
                  <van-radio-group v-model="item.mSnack.value" direction="horizontal">
                    <template v-for="(it) in item.mSnack.option">
                      <van-radio :name="it.value" checked-color="#5d5def">
                        {{ it.label }}
                      </van-radio>
                    </template>
                  </van-radio-group>
                </template>
              </van-field>
              <van-field v-if="item.lunch" name="radio" :label="item.lunch.label" input-align="right">
                <template #input>
                  <van-radio-group v-model="item.lunch.value" direction="horizontal">
                    <van-radio v-for=" (it, index) in item.lunch.option" :key="index" :name="it.value" checked-color="#5d5def">
                      {{ it.label }}
                    </van-radio>
                  </van-radio-group>
                </template>
              </van-field>

              <van-field v-if="item.aSnack" name="radio" :label="item.aSnack.label" input-align="right">
                <template #input>
                  <van-radio-group v-model="item.aSnack.value" direction="horizontal">
                    <template v-for="(it) in item.aSnack.option">
                      <van-radio :name="it.value" checked-color="#5d5def">
                        {{ it.label }}
                      </van-radio>
                    </template>
                  </van-radio-group>
                </template>
              </van-field>
              <van-field v-if="item.dinner" name="radio" :label="item.dinner.label" input-align="right">
                <template #input>
                  <van-radio-group v-model="item.dinner.value" direction="horizontal">
                    <div v-for=" (it, index) in item.dinner.option" :key="index">
                      <van-radio :name="it.value" checked-color="#5d5def">
                        {{ it.label }}
                      </van-radio>
                    </div>
                  </van-radio-group>
                </template>
              </van-field>
            </div>
            <div v-if="!item.diningId" class="noData">
              无可配置用餐信息
            </div>
          </template>
        </div>
      </div>
      <div style="padding: 20px;" class="confirmBtn">
        <van-button type="primary" size="normal" :color="delFlag?'#d85c5c':'#5d5def'" @click="submitConfirm">
          {{ delFlag?'确认删除假条并变更用餐状态':'确认修改假条并变更用餐状态' }}
        </van-button>
        <van-button type="default" size="normal" color="#c6c6c6" plain @click="diningInfoDialog=false;delFlag=false">
          取消
        </van-button>
      </div>
    </van-popup>
    <!-- 用餐信息 End-->   



    <div v-if="isSubmited" class="van-empty">
      <div class="van-empty__image">
        <img :src="okImg">
      </div>
      <div class="errorTip">
        提交成功
      </div>
      <p class="van-empty__description">
        {{ isErrorTip }}
      </p>
      <div style="width: 60%;">
        <van-button round type="primary" color="#5D5DEF" block @click="back()">
          返回上一页
        </van-button>
        <van-button plain round block type="default" url="/shijiwxy/weixin/html/parent/login/index.html">
          返回主页
        </van-button>
      </div>
    </div>

    <div v-if="isError" class="van-empty">
      <div class="van-empty__image">
        <img :src="errorImg">
      </div>
      <div class="errorTip">
        提交失败
      </div>
      <p class="van-empty__description">
        {{ isErrorTip }}
      </p>
      <div style="width: 60%;">
        <van-button round type="primary" color="#5D5DEF" block @click="isError = false; isSubmited = false; isSubmit = false">
          重新提交
        </van-button>
        <van-button plain round block type="default" url="/shijiwxy/weixin/html/parent/login/index.html">
          返回主页
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { Row, Col, Icon, Cell, CellGroup, Tag, Toast } from 'vant';
import { CountDown, Field, Image as VanImage, ImagePreview, RadioGroup, Radio, Checkbox, CheckboxGroup, Button, Sticky, Uploader, Empty, Dialog } from 'vant';
import { Popup, Picker, DatetimePicker, Calendar } from 'vant';
import wechat from '../../util/wechat';
import wx from "weixin-js-sdk";


// import uploadWxImage from '../../util/imgUp/upload'
export default {
  components: {
    [Row.name]: Row,
    [Col.name]: Col,
    [Icon.name]: Icon,
    [Cell.name]: Cell,
    [Tag.name]: Tag,
    [CellGroup.name]: CellGroup,
    [CountDown.name]: CountDown,
    [Icon.name]: Icon,
    [Toast.name]: Toast,
    [Field.name]: Field,
    [VanImage.name]: VanImage,
    [ImagePreview.name]: ImagePreview,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Button.name]: Button,
    [Sticky.name]: Sticky,
    [Uploader.name]: Uploader,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
    [DatetimePicker.name]: DatetimePicker,
    [Calendar.name]: Calendar,
    [Empty.name]: Empty

  },
  data() {
    return {
      errorImg: require("../../assets/img/error.jpg"),
      okImg: require("../../assets/img/ok.jpg"),
      question: [],
      checked: 2,
      checked1: [],
      isUploading: false,
      isSubmit: false,
      isSubmited: false,
      isErrorTip: "",
      isError: false,
      fileList: [],
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2100, 0, 31),
      //时长
      allLong: [],
      //是否代请假
      isNew: false,
      //体温数组
      allTemperatureArray: [
        // 第一列
        {
          values: ['35', '36', '37', '38', '39', '40', '41', '42'],
          defaultIndex: 2,
        },
        {
          values: ['.'],
          defaultIndex: 0,
        },
        // 第二列
        {
          values: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
          defaultIndex: 1,
        },
      ],
      title: '',
      studentInfo: {
        'studentName': '',
        'attnDate': ''
      },
      //当前请假记录Id
      studentRid: '',
      defaultDate: '',
      errmsg: 'https://t.shijiwxy.5tree.cn/eduWeixin/res/respic/1556901624427974656_772_5052493.jpg',
      // 是否开启用餐关联
      attendance: 0,
      // 用餐结束时间
      diningEnd: [],
      //显示数据
      allDiningData: [],
      //显示数据
      saveDiningData: [],
      //当前查看的日期
      activeName: null,
      diningInfoDialog: false,
      //学生问题答案
      allAnswerData: null,
      //旧的用餐信息[学生提交的]
      oldDiningInfo:{},
      //旧的用餐信息[学生提交的]--家长回显用
      oldInfoforParent:{},
      //新的用餐信息[教师修改的]
      newDiningInfo:{},
      //新的用餐信息[学生提交的]--家长回显用
      newInfoforParent:{},
      //是否可编辑用餐
      cansEditRole:false,
      delFlag:false,
      //查询用餐信息
      diningLoading:false,
      oldFlag:1
    };
  }, created() {
    // if (sessionStorage.isSubmited !== undefined) {
    //   this.isSubmited = sessionStorage.isSubmited
    // }

  }, beforeDestroy() {
    //localStorage.removeItem('tempData')
    //Toast.fail('缓存已过期从新返回进入');
  }, mounted() {
 
    const nowTeacherRoles=JSON.parse(sessionStorage.baseUser).orguser.rlids.split(',')
    if(nowTeacherRoles.includes('4') || nowTeacherRoles.includes('21') ||nowTeacherRoles.includes('5')||nowTeacherRoles.includes('50')){
      this.cansEditRole=true
    }

    //获取机构考勤配置  
    this.getDiningOption()  

    //缓存计划信息
    this.studentInfo = JSON.parse(decodeURI(this.$route.query.parameter));
    var promise = new Promise((resolve, reject) => {
      wechat(function () {
        resolve(1)
      })
    });
    promise.then((data) => {
      // 获取学生假条详情
      this.getStuDetail();
    })
    // getStuDetail()
    //生成时长列表
    for (let a = 0.5; a < 10.5; a += 0.5) {
      this.allLong.push(a)
    }
    // 生成标题+'  ('+this.studentInfo.attnDate+')'
    this.title = this.studentInfo.studentName + '请假单'

    //生成默认时间
    var today = new Date()
    var year = today.getFullYear()// 获取年份
    var month = today.getMonth() + 1// 获取月份
    var day = today.getDate()// 获取日期+'  ('+year + '-' + (month<10?'0'+month:month) + '-' + (day<10?'0'+day:day)+')'
    this.defaultDate = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day)
    
  }, methods: {
    dealCheckbox(value,question) {
      //所有的关联都隐藏 2024年1月22日 09:09:50
      question.child.map(item => {
        const showQuestion = this.idAdd(item.toString())
        //被关联且不是答案的隐藏
        this.question[showQuestion[0] - 1].parent = item.id
        if (this.question[showQuestion[0] - 1].child) {
          this.question[showQuestion[0] - 1].child.map(it => {
            const showQuestion = this.idAdd(it.toString())
            //被关联且不是答案的隐藏
            this.question[showQuestion[0] - 1].parent = it.id
          })
        }
      })
      question.option_json.map( item => {
        if(value.includes(item.name) && item.related!==''){
          item.related.split(',').map( ite => {
            const showQuestion = this.idAdd(ite.toString())
            //被关联且不是答案的隐藏
            this.question[showQuestion[0] - 1].parent = ''
            //console.log(this.question[showQuestion[0] - 1])
          })
        }
      })
    },
    // 显示picker
    showPop(item) {
      if ((item.model_type === 6) && item.answer !== '') {
        const answerArray = item.model_type === 6 ? item.answer.split('.') : item.answer.split(':')
        item.columns[0].defaultIndex = item.columns[0].values.indexOf(answerArray[0])
        item.columns[2].defaultIndex = item.columns[2].values.indexOf(answerArray[1])
      }
      item.optionShow = true
    },
    // 禁止输入表情
    checkString(value, obj) {
      const dealValue = value.replace(/(^\s*)|(\s*$)/g, "")
      if (dealValue === '') {
        obj.answer = ''
      } else {
        obj.answer = value.replace(/[^\u4E00-\u9FA5|\d|a-zA-Z|\r\n\s,.?!，。？！…—&$=()-+/*{}[\]]|\s/g, '')
      }
    },
    //显示时长
    showDuration(){
      if(this.question[4].answer ===''|| this.question[5].answer ===''){
        return false
      }
      const startTime=new Date('2000/1/1 '+this.question[4].answer).getTime() 
      const endTime=new Date('2000/1/1 '+this.question[5].answer).getTime() 
      if(startTime>endTime){
        Dialog.alert({
          title: '提示',
          confirmButtonColor: '#06c09b',
          confirmButtonText: '确定',
          message:
            '请假起始时间不能晚于结束时间！',
        }).then(() => {
          this.question[5].answer=''
        });
        this.question[6].answer=''
        return false
      }
      this.question[6].answer=(endTime-startTime)/(1000*60*60).toFixed(2)
    },
    //确认选择答案
    onConfirmOption(value, question) {
      question.optionShow = false
      const nowIndex = question.columns.indexOf(value)
      if (question.model_type === 3) {
        const date = new Date(value)
        const y = date.getFullYear()
        let m = date.getMonth() + 1
        m = m < 10 ? ('0' + m) : m
        let d = date.getDate()
        d = d < 10 ? ('0' + d) : d
        const time = y + '-' + m + '-' + d;
        question.answer = time
      } else {
        question.answer = value
      }
      //<!-- 1文本输入 2下拉单选 3日期选择 4时间选择 5时长选择 6体温选择（统计） 7图片附件 8下拉单选（统计筛选） -->

      if (question.model_type === 6) {
        question.answer = value.join('')
      }
      if (question.model_type === 2 || question.model_type === 8 || question.model_type === 9) {
        //所有的关联都隐藏 2024年1月22日 09:09:50
        question.child.map(item => {
          const showQuestion = this.idAdd(item.toString())
          //被关联且不是答案的隐藏
          this.question[showQuestion[0] - 1].parent = item.id
          if (this.question[showQuestion[0] - 1].child) {
            this.question[showQuestion[0] - 1].child.map(it => {
              const showQuestion = this.idAdd(it.toString())
              //被关联且不是答案的隐藏
              this.question[showQuestion[0] - 1].parent = it.id
            })
          }

        })
        if (question.option_json[nowIndex].related !== '') {
          question.option_json[nowIndex].related.split(',').map(ite => {
            const showQuestion = this.idAdd(ite.toString())
            //被关联且不是答案的隐藏
            this.question[showQuestion[0] - 1].parent = ''
          })
        }
      }
      if (question.model_type === 4 && (question.ref === 'endTime' || question.ref === 'startTime')) {
        this.showDuration()
      }
      if (question.model_type === 3 && (question.title === '开始日期' || question.title === '结束日期')) {
        
        this.newDiningInfo={}
        this.newInfoforParent={}
        if (this.attendance === 1 && this.question[2].answer !== '' && this.question[1].answer !== '' ) {
          const startTime = new Date(this.question[1].answer)
          const endTime = new Date(this.question[2].answer)
          const times = this.generateDates(startTime, endTime,1)
          times.map(item => {
            const now=new Date().getTime()
            const searchTime = new Date(item.replace(/\-/g,'/')).getTime()
            //用餐过了当前时间就不显示
            // if(searchTime>now || item == this.renderTimeStr()){
            this.newDiningInfo[item]={
              diningId: '',
              chineseLabel: this.translateChineseTime(item),
              mealDate:item }
            // }
            //回显记录都显示
            this.newInfoforParent[item]=1
          })
          console.log(this.newInfoforParent)
          this.showAllDate(2,0)
        }
      }
      if (question.model_type === 3 && (question.title === '请假日期')) {
        this.newDiningInfo={}
        this.newInfoforParent={}
        if (this.attendance === 1 && this.question[3].answer !== '' ) {
          const searchTimeStr=this.question[3].answer
          const now=new Date().getTime()
          const searchTime = new Date(searchTimeStr.replace(/\-/g,'/')).getTime()
          //if(searchTime>now){
          this.newDiningInfo[searchTimeStr]={
            chineseLabel: this.translateChineseTime(searchTimeStr),
            mealDate:searchTimeStr,
            diningId: ''
          }
          //  }
          this.newInfoforParent[searchTimeStr]=1
          this.showAllDate(3,0)
        }
      }

      if (question.model_type === 8 && (question.title === '请假类型' && this.attendance === 1)) {
        this.allDiningData = []
      }
    },
    //获取时间段内所有日期
    // type 2 全天假 3小时假
    showAllDate(leaveType,oldFlag) {
      this.oldFlag = oldFlag
      if (this.attendance === 1 && this.question[2].answer !== '' && this.question[1].answer !== '' && leaveType == 2) {
        const startTime = new Date(this.question[1].answer)
        const endTime = new Date(this.question[2].answer)
        this.allDiningData=[]
        if(startTime.getTime()>endTime.getTime()){
          this.question[2].answer=''
          return false
        }
        const times = this.generateDates(startTime, endTime)
        this.getDiningData(times.join(','),oldFlag)

      }
      if (this.attendance === 1 && this.question[3].answer !== '' && leaveType == 3) {
        this.allDiningData=[]
        this.getDiningData(this.question[3].answer,oldFlag)
      }
    },
    //正数
    checkNumber(value, obj) {
      const dealValue = ("" + value).replace(/[^\d^\\.]+/g, "").replace(/^0+(\d)/, "$1").replace(/^\./, "0.").match(/^\d*(\.?\d{0,2})/g)[0] || "" 
      obj.answer = dealValue>24?'24':dealValue
    },
    //单选触发change事件
    handleChange() {
      this.$emit('change')
    },
    // 查询当前id 所在位置
    idAdd(ids) {
      const nowADD = []
      this.question.map((item, index) => {
        if (ids.split(',').map(Number).includes(item.id)) {
          nowADD.push((index) + 1)
        }
      })
      return nowADD
    },
    
    back() {
      window.history.back()
    },
    //------------------------------------------------------------------------------------------------------
    
    //获取时间段内所有的日期
    generateDates(startDate, endDate) {
      const dates = [];
      const currentDate = new Date(startDate);
      const endDateTimestamp = new Date(endDate).getTime();

      while (currentDate.getTime() <= endDateTimestamp) {
        dates.push(currentDate.toJSON().substr(0,10));
        currentDate.setDate(currentDate.getDate() + 1);
      }
      return dates;
    },
    creatTipText(date){
    //&& Object.values(this.newDiningInfo).length>0
      if(Object.values(this.oldDiningInfo).length>0 ){
        if(this.oldDiningInfo[date] && this.newDiningInfo[date]){
          return ''
        }
        if(!this.oldDiningInfo[date] && this.newDiningInfo[date]){
          return '请假'
        }
        if(this.oldDiningInfo[date] && !this.newDiningInfo[date] && this.oldFlag !== 1){
          return '请假取消'
        }
      }
    },
    // 此函数用于将时间转换为中文格式 *月*日
    translateChineseTime(time) {
      const dealTime = new Date(time)
      return (dealTime.getMonth() + 1) + '月' + dealTime.getDate() + '日'
    },
    //时间 2024年7月23日16:54:53 新增--------------------------------------------------------------------------------------------------------------------------------
    // 获取根据日期--用餐信息
    async getDiningData(allDates,oldFlag) {

      Toast.loading({
        message: '正在查询用餐',
        forbidClick: true,
        overlay: true,
      });
      this.diningLoading=true
      const res = await this.$api.base.diningData.get({ 
        mealDates: allDates, 
        studId:this.studentInfo.studentId,
        userId:this.studentInfo.studentUserId });
      if (res.code === 200) {
        const stopTimes = res.data.todayReport.endTime.split(',');
        if (stopTimes.length < 5) {
          const lastTime = stopTimes[stopTimes.length - 1];
          while (stopTimes.length < 5) {
            stopTimes.push(lastTime);
          }
        }

        //this.newDiningInfo={}
        
        const dealData = [];
        const nowTime = new Date().getTime();

        //判断是否有不用餐的日期
        const allDatesArray=allDates.split(',').filter(item => {
          return (nowTime < new Date(item).getTime()|| (nowTime > new Date(item).getTime() && (this.renderTimeStr()==this.renderTimeStr(item))))
        })
        const allDatesObj={}
 
        // 创建用餐选项的函数
        const createMealOption = (item, target, label, stopTimeIndex) => {
          return {
            option: [
              {
                value: Math.abs(target),
                label: '用餐'
              },
              {
                value: 0 - Math.abs(target),
                label: '不用餐'
              },
            ],
            label: label,
            value: this.oldDiningInfo[item.mealDate]?target:0 - Math.abs(target),
            stop: nowTime > new Date(item.mealDate + " " + stopTimes[stopTimeIndex]).getTime()
          };
        };

        // 遍历餐厅列表数据
        res.data.diningList.forEach(item => {
          // 创建一个处理对象，包含餐厅ID和用餐日期
          const dealObj = {
            diningId: item.diningId,
            mealDate: item.mealDate,
            chineseLabel: this.translateChineseTime(item.mealDate)
          };
          let dingingNumber=0

          const dealTimes = function(time){
            const tomorrow = new Date(item.mealDate.replace(/\-/g,'/'));
            const itemDeal=time.split(':').map(Number)

            if(item.mealDate== res.data.todayReport.reportDate || tomorrow.getTime()< nowTime){
              if(itemDeal[0]>=24){
                tomorrow.setHours(itemDeal[0]-24)
                tomorrow.setMinutes(itemDeal[1])
              }else{
                tomorrow.setHours(itemDeal[0])
                tomorrow.setMinutes(itemDeal[1])
              }
            }else{
              if(itemDeal[0]>=24){
                tomorrow.setDate(tomorrow.getDate() + 1);
                tomorrow.setHours(itemDeal[0]-24)
                tomorrow.setMinutes(itemDeal[1])
              }else{
                tomorrow.setHours(itemDeal[0])
                tomorrow.setMinutes(itemDeal[1])
              }
            } 
            return tomorrow.getTime()
          }

          // 如果预订早餐目标不为0，则添加早餐选项
          if (item.bookBreakfastTarget !== 0 && nowTime < dealTimes(stopTimes[0])) {
            dealObj.breakfast = createMealOption(item, item.bookBreakfastTarget, '早餐', 0);
            dingingNumber+=1
          }
          // 如果预订上午点心目标不为0，则添加上午点心选项
          if (item.bookMSnackTarget !== 0 && nowTime < dealTimes(stopTimes[1])) {
            dealObj.mSnack = createMealOption(item, item.bookMSnackTarget, '上午点心', 1);
            dingingNumber+=1
          }

          // 如果预订午餐目标不为0，则添加午餐选项
          if (item.bookLunchTarget !== 0 && nowTime < dealTimes(stopTimes[2])) {
            dealObj.lunch = createMealOption(item, item.bookLunchTarget, '午餐', 2);
            dingingNumber+=1
          }

          // 如果预订下午点心目标不为0，则添加下午点心选项
          if (item.bookASnackTarget !== 0 && nowTime < dealTimes(stopTimes[3])) {
            dealObj.aSnack = createMealOption(item, item.bookASnackTarget, '下午点心', 3);
            dingingNumber+=1
          }

          // 如果预订晚餐目标不为0，则添加晚餐选项
          if (item.bookDinnerTarget !== 0 && nowTime < dealTimes(stopTimes[4])) {
            dealObj.dinner = createMealOption(item, item.bookDinnerTarget, '晚餐', 4);
            dingingNumber+=1
          }

          // // ==1 是无用餐 2 有用餐 但是过期
          // if(this.oldDiningInfo[item.mealDate] && dingingNumber==0 ){
          //   // this.oldDiningInfo[item.mealDate] = 2
          // }
 
          if(dingingNumber>0 &&(nowTime < new Date(item.mealDate.replace(/\-/g,'/') ).getTime()|| (nowTime > new Date(item.mealDate.replace(/\-/g,'/') ).getTime() && (this.renderTimeStr()==this.renderTimeStr(item.mealDate))))){
            //生成备份
            if(oldFlag){
              this.oldDiningInfo[item.mealDate]=dealObj
            }else{
              this.newDiningInfo[item.mealDate]=dealObj
            }
            // 将处理对象添加到处理数据数组中
            //dealData.push(dealObj);
            allDatesObj[item.mealDate]=dealObj
          }
        });

        const _this=this
        _this.allDiningData=[]
        //
        allDatesArray.map(item => {
          if(allDatesObj[item]){
            _this.allDiningData.push(allDatesObj[item])
          }else{
            if(_this.oldDiningInfo[item]){
              _this.allDiningData.push(_this.oldDiningInfo[item])
            }
            if(_this.newDiningInfo[item]&&!_this.oldDiningInfo[item]){
              _this.allDiningData.push(_this.newDiningInfo[item])
            }
          }
        })

        // this.activeName = this.allDiningData[0].mealDate
        this.diningLoading=false
        //  字段说明
        // 1 bookBreakfastAdditional: 早餐陪餐---
        // bookBreakfastTarget: 早餐
        // 2 bookMSnackAdditional:上午点心陪餐---
        // bookMSnackTarget: 上午点心
        // 3 bookLunchAdditional: 午餐陪餐---
        // bookLunchTarget: 午餐
        // 4 bookASnackAdditional:  下午点心陪餐----
        // bookASnackTarget:  下午点心
        // 5 bookDinnerAdditional: 晚餐陪餐---
        // bookDinnerTarget: 晚餐
        // attendance: 0 是否开启考勤关联
        // role: "4,21"  可编辑用餐上报明细的角色 4 班主任 5 年级主任  21用餐管理员 50 配餐公司
        Toast.clear();

      } else {
        Toast.fail(res.message);
      }
    },

    // 查询机构配置
    async getDiningOption() {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        overlay: true,
      });
      const res = await this.$api.base.diningOption.get({mealDates:'2024-07-22,2024-07-31',userId:''});
      Toast.clear();
      if (res.code === 200) {
        this.attendance=res.data.attendance
        //用到的字段
        // attendance: 0 是否开启考勤关联
        // role: "4,21"  可编辑用餐上报明细的角色 4 班主任 5 年级主任  21用餐管理员 50 配餐公司
      } else {
        Toast.fail(res.message);
      }
    },

    // 保存用餐设置
    async saveStuDining(setData,callback,type) {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        overlay: true,
      });
      const saveData=JSON.parse(JSON.stringify(setData)).filter(item => item.diningId!=='')
      const res = await this.$api.base.stuDiningSet.post({
        customRule:JSON.stringify(saveData),
        studId:this.studentInfo.studentId,
        sUserId:''
      });
      Toast.clear();
      if (res.code === 200) {
        if(callback){
          callback()
        }
        if(type==1){
         
          Dialog.alert({
            title: '提示',
            confirmButtonColor: '#5D5DEF',
            confirmButtonText: '确定',
            message: '假条已删除',
          }).then(() => {
            window.history.back()
          });
           
        }else{
          Dialog.alert({
            title: '提示',
            confirmButtonColor: '#5D5DEF',
            message: this.isNew ? "请假成功！" : "修改成功！"
          }).then(() => {
            window.history.back()
          });
        }
      } else {
        //Toast.fail(res.message);
        Dialog.alert({
          title: '提示',
          confirmButtonColor: '#06c09b',
          message: "请假成功,用餐信息变更失败！",
        }).then(() => {
          // window.location = "../index_new.html"
          window.history.back()
        });
         
      }
    },
    //时间转年月日格式(年-月-日格式)
    renderTimeStr(date){
      return date?new Date(date).toJSON().substr(0,10):new Date().toJSON().substr(0,10)
    },
    //------------------------------------------------------------------------------------------------------
    // 假条设置为已读
    async recordIsRead(okFun) {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        overlay: true,
      });
      const res = await this.$api.base.recordRead.post({ 'recordIds': this.studentRid });
      Toast.clear();
      if (res.code === 200) {
        Toast.success('假条已读！');
      } else {
        Toast.fail(res.message);
      }
    },
    // 删除考勤请假记录
    async delRecord(okFun) {
      
      if (this.attendance == 1 && this.allDiningData.length>0) {
        // 取消的日期
        const cancelDates={}
        if(Object.values(this.oldDiningInfo).length>0 && Object.values(this.newDiningInfo).length>0){
          for(const item in this.oldDiningInfo){
            if(this.newDiningInfo[item]==undefined){
              const dealObj=this.oldDiningInfo[item]
              // 如果预订早餐目标不为0，则添加早餐选项
              if (dealObj.breakfast) {
                dealObj.breakfast.value = Math.abs(dealObj.breakfast.value)
              }
              // 如果预订上午点心目标不为0，则添加上午点心选项
              if (dealObj.mSnack) {
                dealObj.mSnack.value = Math.abs(dealObj.mSnack.value)//createMealOption(item, item.bookMSnackTarget, '上午点心', 1);
              }
              // 如果预订午餐目标不为0，则添加午餐选项
              if (dealObj.lunch) {
                dealObj.lunch.value = Math.abs(dealObj.lunch.value)//createMealOption(item, item.bookLunchTarget, '午餐', 2);
              }

              // 如果预订下午点心目标不为0，则添加下午点心选项
              if (dealObj.aSnack) {
                dealObj.aSnack.value = Math.abs(dealObj.aSnack.value)//createMealOption(item, item.bookASnackTarget, '下午点心', 3);
              }
              // 如果预订晚餐目标不为0，则添加晚餐选项
              if (dealObj.dinner) {
                dealObj.dinner.value = Math.abs(dealObj.dinner.value)//createMealOption(item, item.bookDinnerTarget, '晚餐', 4);
              }
              cancelDates[item]=this.oldDiningInfo[item]
            }
          }
          // console.log(cancelDates)
          // console.log(Object.values(cancelDates).sort((a,b)=> a.mealDate.localeCompare(b.mealDate)))
          const cancelValues=Object.values(cancelDates)

          //按日历排序
          this.saveDiningData=[...cancelValues,...this.allDiningData].sort((a,b) => a.mealDate.localeCompare(b.mealDate))
        } else{
          this.saveDiningData=[...this.allDiningData].sort((a,b) => a.mealDate.localeCompare(b.mealDate))
        }

        this.diningInfoDialog = true;    
        this.delFlag=true
        this.confirmBtnText='确认删除假条并变更用餐状态'

      }else{
        Dialog.confirm({
          title: '提示',
          confirmButtonColor: '#5d5def',
          message: '确定删除' + this.studentInfo.studentName + '请假单?',
        })
          .then(async () => {
            this.toDelRecord(function(){
              Dialog.alert({
                title: '提示',
                confirmButtonColor: '#5D5DEF',
                confirmButtonText: '确定',
                message: '假条已删除',
              }).then(() => {
                window.history.back()
              });
            })
          })
      }

      // Dialog.confirm({
      //   title: '提示',
      //   confirmButtonColor: '#5d5def',
      //   message: '确定删除' + this.studentInfo.studentName + '请假单?',
      // })
      // .then(async () => {
      //   Toast.loading({
      //     message: '加载中...',
      //     forbidClick: true,
      //     overlay: true,
      //   });
      //   const res = await this.$api.base.delRecord.post({ 'id': this.studentRid });
      //   Toast.clear();
      //   if (res.code === 200) {
      //     // this.isSubmited = true;
      //     // this.isErrorTip='假条已删除'
      //     Dialog.alert({
      //       title: '提示',
      //       confirmButtonColor: '#5D5DEF',
      //       confirmButtonText: '确定',
      //       message: '假条已删除',
      //     }).then(() => {
      //       window.history.back()
      //     });
      //   } else {
      //     Toast.fail(res.message);
      //   }
      // })
    },
    // 删除考勤请假记录
    async toDelRecord(okFun) {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        overlay: true,
      });
      const res = await this.$api.base.delRecord.post({ 'id': this.studentRid });
      Toast.clear();
      if (res.code === 200) {
        // this.isSubmited = true;
        // this.isErrorTip='假条已删除'
        if(okFun){
          okFun()
        }
      } else {
        Toast.fail(res.message);
      }
    },
    //获取个人请假详情detail
    async getStuDetail() {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        overlay: true,
      });
      const res = await this.$api.base.detail.get({
        stud_id: this.studentInfo.studentId,
        leave_date: this.studentInfo.attnDate
      });

      if (res.code === 200) {
        Toast.clear();
        this.studentRid = res.data.leave_record ? res.data.leave_record.id : ''
        //设置为已读
        if (res.data.leave_record && res.data.leave_record.is_read !== 1) {
          this.recordIsRead()
        }
        // 判断是否代请假
        if (res.data.leave_record) {
          this.isNew = false
        } else {
          this.isNew = true
        }

        //答案
        let answerArray = res.data.leave_map

        if (res.data.leave_record === undefined || res.data.leave_record.class_id !== Number(this.studentInfo.classId)) {
          answerArray = []
        }
        //生成题目 
        this.question = res.data.leave_model_list.map((item, index) => {
          item.parent = ''
          //<!-- 1文本输入 2下拉单选 3日期选择 4时间选择 5时长选择 6体温选择（统计） 7图片附件 8下拉单选（统计筛选） -->
          //除了文本和日期还有图片都要生成选项
          if (item.model_type !== 1 || item.model_type !== 3 || item.model_type !== 7) {
            item.answer = answerArray.length === 0 ? '' : (res.data.leave_record ? (answerArray[item.id].value === '' || answerArray[item.id].value === null ? '' : answerArray[item.id].value) : '')
            item.rid = answerArray.length === 0 ? '' : (res.data.leave_record ? (answerArray[item.id].id === '' || answerArray[item.id].id === null ? '' : answerArray[item.id].id) : '')
            item.columns = []
            item.optionShow = false
          }
          //图片类型
          if (item.model_type === 7) {
            if (item.answer !== '') {
              item.pic = item.answer.split(',').map(ite => {
                return { url: ite }
              })
            } else {
              item.pic = []
            }
          }

          //日期
          if (item.model_type === 4 &&(item.title === '起始时间'||item.title === '结束时间')) {
            item.ref = item.title === '起始时间'?'startTime':(item.title === '结束时间'?'endTime':'')
          }
          //图片类型
          if (item.model_type === 9) {
            //item.answer=[]
            item.answer=item.answer===''?[]:item.answer.split(',')
          }
          //时长(注入可选择范围)
          if (item.model_type === 5) {
            item.columns = this.allLong.map(String)
            //回显
            item.default = item.columns.indexOf(item.answer)
          }

          //体温(注入可选择范围)
          if (item.model_type === 6) {
            item.columns = this.allTemperatureArray
            if (item.answer !== '') {
              const answer = item.answer.split('.') // answerArray[item.id].value.split('.')
              this.allTemperatureArray[0].defaultIndex = this.allTemperatureArray[0].values.indexOf(answer[0])
              this.allTemperatureArray[2].defaultIndex = this.allTemperatureArray[2].values.indexOf(answer[1])
            }
          }
          //体温
          //   if (item.model_type === 4) {
          //     item.columns = this.allTemperatureArray
          //     if(item.answer!==''){
          //         const answer=item.answer.value.split('.') // answerArray[item.id].value.split('.')
          //         this.allTemperatureArray[0].defaultIndex= this.allTemperatureArray[0].values.indexOf(answer[0])
          //         this.allTemperatureArray[2].defaultIndex= this.allTemperatureArray[2].values.indexOf(answer[1])
          //         //回显
          //         console.log(this.allTemperatureArray)
          //     }
          //   }
          //下拉
          if (item.model_type === 2 || item.model_type === 8 || item.model_type === 9) {
            item.option_json = item.option_json === '' ? [] : JSON.parse(item.option_json)
            item.child = []
            item.option_json.map((it, i) => {
              //生成弹出选择
              item.columns.push(it.name)
              if (item.answer === it.name) {
                item.default = i
              }
              //关联项整理
              if (it.related !== '' && it.related !== undefined) {
                it.related.split(',').map(ite => {
                  item.child.push(ite)
                  this.$nextTick(() => {
                    const showQuestion = this.idAdd(ite.toString())
                    if (showQuestion.length > 0 && item.answer !== it.name) {
                      this.question[showQuestion[0] - 1].parent = item.id
                    }
                  })
                })
              }
            }) 
          }
          if (item.model_type === 9) {
            item.option_json.map((it, i) => {
              //关联项整理
              if (it.related !== '' && it.related !== undefined) {
                it.related.split(',').map(ite => {
                  item.child.push(ite)
                  this.$nextTick(() => {
                    const showQuestion = this.idAdd(ite.toString())
                    if (showQuestion.length > 0 && item.answer.includes(it.name)) {
                      this.question[showQuestion[0] - 1].parent = ''
                    }
                  })
                })
              }
            }) 
          }
          item.is_required = item.is_required === 1
          return item
        })
 
        // console.log(this.question)
        this.oldDiningInfo={}
        //查询用餐信息
        if (this.question[0].answer === '全天假') {
          this.showAllDate(2,1)
          if (this.attendance === 1 && this.question[2].answer !== '' && this.question[1].answer !== '' ) {
            const startTime = new Date(this.question[1].answer)
            const endTime = new Date(this.question[2].answer)
            const times = this.generateDates(startTime, endTime,1)
            const now= Date.now()
            times.map(item => {
              const searchTime = new Date(item).getTime()
              //用餐信息
              if(searchTime > now || item == this.renderTimeStr()){
                this.oldDiningInfo[item]={
                  diningId: '',
                  chineseLabel: this.translateChineseTime(item),
                  mealDate:item }
              }
              //家长回显用餐信息
              this.oldInfoforParent[item]=1
            })
          }
        } else {
          this.showAllDate(3,1)
          if (this.attendance === 1 && this.question[3].answer !== '' ) {
            const searchTimeStr=this.question[3].answer
            const now= Date.now()
            const searchTime = new Date(searchTimeStr).getTime()
            if(searchTime>now || searchTimeStr == this.renderTimeStr()){
              this.oldDiningInfo[searchTimeStr]={
                chineseLabel: this.translateChineseTime(searchTimeStr),
                mealDate:searchTimeStr,
                diningId: ''
              }
            }
            //家长回显用餐信息
            this.oldInfoforParent[searchTimeStr]=1
          }
        }

      } else {
        Toast.fail(res.message);
      }
    },
    wxCImg(item) {
      const that = this
      let imgList = item.pic
      let localImages = []

      //选图
      new Promise((resolve, reject) => {
        wx.chooseImage({
          count: 9 - imgList.length,
          sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有'compressed' original
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            //rows="";//声明一个空字符串用于保存循环出来的html
            localImages = localImages.concat(res.localIds); // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            //imgList = imgList.unique();
            if (window._wxjs_is_wkwebview || !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) { //判断ios是不是用的 wkwebview 内核
              const m = 0, n = localImages.length;
              (function loadData(m) {
                wx.getLocalImgData({
                  localId: localImages[m], // 需要上传的图片的本地ID，由chooseImage接口获得
                  success: function (res) {
                    const localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                    //localData = localData.replace('jgp', 'jpeg');//iOS 系统里面得到的数据，类型为 image/jgp,因此需要替换一下
                    imgList.push({
                      'file': {},
                      'url': localData,
                      'localId': localImages[m],
                      'isImage': true,
                      'status': 'uploading',
                      'message': '上传中...',
                      'serverId': '',
                      'content': localData
                    })
                    if (m < (n - 1)) {
                      loadData(m + 1);
                    } else {
                      resolve(1)
                    }
                  }
                });
              }(m));
            } else { //如果不是用的wkwebview 内核 或者是用的安卓系统 执行下面
              imgList = localImages.map(item => {
                return {
                  'file': {},
                  'url': item,
                  'status': 'uploading',
                  'message': '上传中...',
                  'isImage': true,
                  'serverId': '',
                  'localId': item,
                  'content': item
                }
              })
              item.pic = item.pic.concat(imgList)

              resolve(1)
            }
          }
        })
      }).then(() => {
        const m = 0, n = imgList.length;
        this.isUploading = true;

        //上传
        // eslint-disable-next-line no-unexpected-multiline
        (function upIMG(m) {
          //解决老图片问题

          if (imgList[m].localId !== undefined) {

            wx.uploadImage({
              localId: imgList[m].localId, // 需要上传的图片的本地ID，由chooseImage接口获得
              isShowProgressTips: 1,
              success: function (res) {

                const localData = res.serverId; // localData是图片的base64数据，可以用img标签显示
                imgList[m].serverId = localData
                if (m < (n - 1)) {
                  upIMG(m + 1);
                } else {
                  that.wxImgUp(imgList)
                }
              }
            });
          } else {
            if (m < (n - 1)) {
              upIMG(m + 1);
            }
          }
        }(m))
      })
    },
    // 学生提交
    async submit() {

      if(this.diningLoading){
        Toast.loading({
          message: '正在查询用餐...',
          forbidClick: true,
          overlay: true,
        });
        return false
      }

      if (this.question.length === 0) {
        Dialog.alert({
          title: '提示',
          confirmButtonColor: '#5D5DEF',
          confirmButtonText: '刷新',
          message:
            '操作失败！当前网络异常，请刷新页面后重试。',
        }).then(() => {
          window.location.reload()
        });
        return false
      }

      if (this.isUploading) {
        Toast.fail({ message: "图片正在上传请稍候！", duration: 3000 });
        // closeOnClick: true, onClose: function{ }
        return false
      }

      var isUprechecked = null

      //整理答案
      const allAnswer = [];
      const unAnswer = [];
      this.question.map((item, index) => {
        //判断是否未填
        if (item.pic && item.pic.length === 0 && item.model_type === 7 && item.is_required && item.parent === '') {
          unAnswer.push(item.title)
        }
        if (item.answer === '' && item.model_type !== 7 && item.model_type !== 7 && item.is_required && item.parent === '') {
          unAnswer.push(item.title)
        }

        if (item.model_type === 7) {
          item.pic.map((v) => {
            if (v.status === 'uploading') {
              isUprechecked === true
            }
          })
        }

        if (item.answer.length === 0 && item.model_type === 9 && item.is_required && item.parent === '') {
          unAnswer.push(item.title)
        }

        var obj = {
          "id": item.rid,
          "model_id": item.id,
          "key": "",
          "value": item.model_type === 7 ? item.pic.map(ite => { return ite.url.includes('http') ? ite.url : window.location.origin + ite.url }).join(",") : (item.parent !== '' ? '' : (item.model_type === 9?item.answer.join(','):item.answer)),
        }
        allAnswer.push(obj)
      })

      //多张图上传
      if (isUprechecked) {
        Toast.fail({ message: "图片正在上传请稍候！", duration: 3000 });
        return false
      }
      if (unAnswer.length > 0) {
        Dialog.alert({
          title: '提示',
          message: unAnswer.join(',') + "未填写!",
        }).then(() => {
          // on close
        });
        return false
      }

      this.allAnswerData = allAnswer
      this.saveDiningData=[]

      console.log(this.oldDiningInfo)
      console.log(this.newDiningInfo)
      console.log(this.oldFlag) 
      //是否用餐关联 
      if (this.attendance == 1 && (this.allDiningData.length>0 || Object.values(this.oldDiningInfo).length>0)) {
        // 取消的日期
        const cancelDates={}
        //&& Object.values(this.newDiningInfo).length>0
        if(Object.values(this.oldDiningInfo).length>0 && !this.oldFlag){
          for(const item in this.oldDiningInfo){
            if(this.newDiningInfo[item]==undefined){
              const dealObj=this.oldDiningInfo[item]
              // 如果预订早餐目标不为0，则添加早餐选项
              if (dealObj.breakfast) {
                dealObj.breakfast.value = Math.abs(dealObj.breakfast.value)
              }
              // 如果预订上午点心目标不为0，则添加上午点心选项
              if (dealObj.mSnack) {
                dealObj.mSnack.value = Math.abs(dealObj.mSnack.value)//createMealOption(item, item.bookMSnackTarget, '上午点心', 1);
              }
              // 如果预订午餐目标不为0，则添加午餐选项
              if (dealObj.lunch) {
                dealObj.lunch.value = Math.abs(dealObj.lunch.value)//createMealOption(item, item.bookLunchTarget, '午餐', 2);
              }

              // 如果预订下午点心目标不为0，则添加下午点心选项
              if (dealObj.aSnack) {
                dealObj.aSnack.value = Math.abs(dealObj.aSnack.value)//createMealOption(item, item.bookASnackTarget, '下午点心', 3);
              }
              // 如果预订晚餐目标不为0，则添加晚餐选项
              if (dealObj.dinner) {
                dealObj.dinner.value = Math.abs(dealObj.dinner.value)//createMealOption(item, item.bookDinnerTarget, '晚餐', 4);
              }
              cancelDates[item]=this.oldDiningInfo[item]
            }

          }
          // console.log(cancelDates)
          // console.log(Object.values(cancelDates).sort((a,b)=> a.mealDate.localeCompare(b.mealDate)))
          const cancelValues=Object.values(cancelDates)
          //按日历排序
           
          this.saveDiningData=[...cancelValues,...this.allDiningData].sort((a,b) => a.mealDate.localeCompare(b.mealDate))
          
          
        } else{
          this.saveDiningData=[...this.allDiningData].sort((a,b) => a.mealDate.localeCompare(b.mealDate))
        }
        console.log(this.saveDiningData)
        this.diningInfoDialog = true;    
      } else {
        this.submitLeave(allAnswer)
      }
      // Toast.loading({
      //   message: '保存中...',
      //   forbidClick: true,
      //   overlay: true,
      // });

      // 提交格式 一个表现下的题放到一起~
      // const nowStudent = this.studentInfo
      // const parameter = {
      //   gradeId: nowStudent.gradeId,
      //   classId: nowStudent.classId,
      //   studentUserId: nowStudent.studentUserId,
      //   studentId: nowStudent.studentId,
      //   studentName: nowStudent.studentName,
      //   applicant: 1,
      //   id: this.studentRid,
      //   //申请人（0：家长；1：教师）
      //   applicant_name: JSON.parse(sessionStorage.baseUser).orguser.teacher.tech_name,
      //   leave_record_json: JSON.stringify(allAnswer)
      // }
      // const res = await this.$api.base.submit.post(parameter);
      // Toast.clear()
      // if (res.code === 200) {
      //   Dialog.alert({
      //     title: '提示',
      //     confirmButtonColor: '#5D5DEF',
      //     message: this.isNew ? "请假成功！" : "修改成功！"
      //   }).then(() => {
      //     window.history.back()
      //   });
      // } else {
      //   Toast.fail(res.message);
      // }

    },
    //确认用餐信息
    submitConfirm() {
      const subData = []
      this.saveDiningData.map(item => {
        // 创建一个处理对象，包含餐厅ID和用餐日期
        const dealObj = {
          diningId: item.diningId,
          mealDate: item.mealDate
        };
        // 如果预订早餐目标不为0，则添加早餐选项
        if (item.breakfast) {
          dealObj.breakfast = this.delFlag?Math.abs(item.breakfast.value):item.breakfast.value
        }
        // 如果预订上午点心目标不为0，则添加上午点心选项
        if (item.mSnack) {
          dealObj.mSnack = this.delFlag?Math.abs(item.mSnack.value):item.mSnack.value
        }
        // 如果预订午餐目标不为0，则添加午餐选项
        if (item.lunch) {
          dealObj.lunch = this.delFlag?Math.abs(item.lunch.value):item.lunch.value
        }
        // 如果预订下午点心目标不为0，则添加下午点心选项
        if (item.aSnack) {
          dealObj.aSnack = this.delFlag?Math.abs(item.aSnack.value):item.aSnack.value
        }
        // 如果预订晚餐目标不为0，则添加晚餐选项
        if (item.dinner) {
          dealObj.dinner = this.delFlag?Math.abs(item.dinner.value):item.dinner.value
        }
        // 将处理对象添加到处理数据数组中
        if (item.dinner||item.aSnack||item.lunch||item.mSnack||item.breakfast) {
          subData.push(dealObj);
        }
      });
      
      const saveStuDiningInfo={
        'meal_information':JSON.stringify(this.newInfoforParent),
        'old_meal_information':JSON.stringify(this.oldInfoforParent)
      }


      var promise = new Promise((resolve, reject) => {
        if(this.delFlag){
          this.toDelRecord(function(){
            resolve(1)
          })
        }else{
          this.leaveInfoSub(this.allAnswerData,saveStuDiningInfo,function(){
            resolve(2)
          })
        }
      });

      promise.then((data) => {
        this.diningInfoDialog = false;
        if(subData.length>0){
          this.saveStuDining(subData,null,data)
        }else{
          if(data==1){
            Dialog.alert({
              title: '提示',
              confirmButtonColor: '#5D5DEF',
              confirmButtonText: '确定',
              message: '假条已删除',
            }).then(() => {
              window.history.back()
            });
          }else{
            Dialog.alert({
              title: '提示',
              confirmButtonColor: '#5D5DEF',
              message: this.isNew ? "请假成功！" : "修改成功！"
            }).then(() => {
              window.history.back()
            });
          }
        }
      });
    },
    // 学生提交请假确认
    submitLeave(allAnswer) {
      Dialog.confirm({
        title: '提示',
        confirmButtonColor: '#06c09b',
        message: '要立刻提交吗？提交后不可修改，请仔细检查填写内容！',
      })
        .then(() => {
          this.leaveInfoSub(allAnswer)
        })
        .catch(() => {
          this.isSubmit = false;
          // on cancel
        });
    },
    //提交学生请假
    async leaveInfoSub(allAnswer,diningData,okFun) {
      Toast.loading({
        message: '保存中...',
        forbidClick: true,
        overlay: true,
      });
      // 提交格式 一个表现下的题放到一起~

      // 提交格式 一个表现下的题放到一起~
      const nowStudent = this.studentInfo
      
      const parameter = Object.assign({
        gradeId: nowStudent.gradeId,
        classId: nowStudent.classId,
        studentUserId:'',
        studentId: nowStudent.studentId,
        studentName: nowStudent.studentName,
        applicant: 1,
        id: this.studentRid,
        //申请人（0：家长；1：教师）
        applicant_name: JSON.parse(sessionStorage.baseUser).orguser.teacher.tech_name,
        leave_record_json: JSON.stringify(allAnswer)
      },diningData||{})


      const res = await this.$api.base.submit.post(parameter);
      Toast.clear()
      if (res.code === 200) {
        if(okFun){
          okFun()
        }else{
          Dialog.alert({
            title: '提示',
            confirmButtonColor: '#5D5DEF',
            message: this.isNew ? "请假成功！" : "修改成功！"
          }).then(() => {
            window.history.back()
          });
        }
        // Dialog.alert({
        //   title: '提示',
        //   confirmButtonColor: '#5D5DEF',
        //   message: this.isNew ? "请假成功！" : "修改成功！"
        // }).then(() => {
        //   window.history.back()
        // });
      } else {
        Dialog.alert({
          message: res.message,
        })
      }



      // const nowStudent = JSON.parse(sessionStorage.nowStudent)
      // const parameter = {
      //   gradeId: nowStudent.classList[0].grade_id,
      //   classId: nowStudent.classList[0].clas_id,
      //   studentUserId: nowStudent.user_id,
      //   studentId: nowStudent.stud_id,
      //   studentName: nowStudent.stud_name,
      //   applicant: 0,
      //   //申请人（0：家长；1：教师）
      //   applicant_name: nowStudent.stud_name,
      //   leave_record_json: JSON.stringify(allAnswer)
      // }
      // const res = await this.$api.base.submit.post(parameter);
      // Toast.clear()
      // if (res.code === 200) {
      //   Dialog.alert({
      //     title: '提示',
      //     confirmButtonColor: '#06c09b',
      //     message: "请假成功！",
      //   }).then(() => {
      //     window.location = "../index_new.html"
      //   });
      // } else {
      //   //Toast.fail(res.message);
      //   Dialog.alert({
      //     message: res.message,
      //   })
      // }
    },

    // 微信图片上传
    async wxImgUp(files) {

      const oldObj = [];
      //提交ID
      const changeObj = []

      files.map((item, i) => {

        if (item.serverId === undefined) {
          oldObj.push(item)
        } else {
          changeObj.push(item)
        }
      })
      const subIds = changeObj.map((item) => item.serverId)
      if (this.isSubmit) {
        return false
      }
      // 提交格式 一个表现下的题放到一起~
      const parameter = {
        mediaIds: JSON.stringify(subIds),
      }
      Toast.loading({
        message: '',
        forbidClick: true,
        overlay: true,
      });
      const res = await this.$api.base.wxUpload.post(parameter);
      Toast.clear()
      if (res.code === 200) {
        changeObj.map((file, index) => {
          file.url = '/eduWeixin/res/respic/' + res.data[index];
          file.status = '';
          file.message = '';
        });
        files = [...oldObj, ...changeObj]
        this.isUploading = false
      } else {
        Toast.fail(res.message);
      }
    },
    //图片预览
    imgView(item, index) {
      ImagePreview({
        images: item,
        startPosition: index
      });
    }, checkedImg(file) {
      if (file.name === undefined && file.length > 9) {
        Toast.fail("最多选取9张图片");
        return false
      } else {
        return true
      }

    },
  }
};
</script>

<style lang="less" scoped>
@bzcolor: #24bfa0;

::v-deep .van-tag--questionType {
  //background-color: @bzcolor;
  padding: 2px 4px;
  margin-top: 1vw;
  margin-right: 2vw;
  color: red;
}

::v-deep .custom-title {
  font-weight: bold;
  margin-top: 0.6vw;
  font-size: 3.6vw;
}

// ::v-deep .van-cell::after {
//     border-bottom: none;
// }

::v-deep .van-cell__title {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
}

// ::v-deep .van-cell-group {
//   margin: 3vw 0;
//   padding-top: 5px;
// }

// ::v-deep .van-field {
//   background: #f4f5f7;
//   border-radius: 1vw;
// }

::v-deep .questionDescription {
  margin-bottom: 3vw;
}

::v-deep .questionPic {
  padding-bottom: 3vw;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: justify;
  -webkit-justify-content: flex-start;
  justify-content: flex-start;
  flex-wrap: wrap;
}

::v-deep .van-radio,
.van-checkbox {
  margin-bottom: 3vw;
}

::v-deep .van-radio__icon--checked .van-icon,
.van-checkbox__icon--checked .van-icon {
  background-color: @bzcolor;
  border-color: @bzcolor;
}

::v-deep .bottomTool {
  bottom: 0;
  right: 0;
  left: 0;
  z-index: 99;
  top: auto;
  position: fixed;
  padding: 3vw;
  background: #fff;
  box-shadow: 0px -3px 6px 0px #efeeeecc;
}

::v-deep .oneQuestionWrap {
  padding: 0px 20px 24px 10vw;
  display: flow-root;
}

::v-deep .errorTip {
  font-weight: bold;
  padding-top: 2vw;
}

::v-deep button+button {
  margin-top: 0px;
  color: #8f8f8f;
  border-color: #dddee0;
}

//   ::v-deep .van-button--primary {
//       color: #fff;
//       background-color: #5D5DEF;
//       border: 1px px solid #5D5DEF;
//   }

//   ::v-deep .van-checkbox__icon--checked .van-icon {
//       color: #fff;
//       background-color: #5D5DEF;
//       border-color: #5D5DEF;
//   }

::v-deep .van-empty__image {
  width: 200px;
  height: auto;
}

// ::v-deep .van-field__control {
//   padding-right: 5px;
//   min-height: 148px;
// }

.imgWrap {
  margin-right: 10px;
  margin-bottom: 10px;
}

/* // ::v-deep .van-uploader__wrapper .van-uploader__upload {
      //   display: none;
      // } */
::v-deep .van-uploader__upload1 {
  position: relative;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  flex-direction: column;
  -webkit-box-align: center;
  -webkit-align-items: center;
  align-items: center;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  box-sizing: border-box;
  width: 72px;
  height: 72px;
  margin: 0 8px 8px 0;
  background-color: #f7f8fa;

  input {
    display: none;
  }
}

::v-deep .van-uploader__input {
  display: none;
}

::v-deep div,
.van-cell {
  word-break: break-all;
}

::v-deep .storageBtn {
  color: #fdfdfd;
  background: #5D5DEF;
  border-color: #a6e6e6;
}

::v-deep .van-checkbox__icon--checked .van-icon {
  color: #fff;
  background-color: #5D5DEF;
  border-color: #5D5DEF;
}

.van-block__title {
  margin: 0;
  padding: 22px 16px 10px;
  color: rgba(69, 90, 100, 0.6);
  font-weight: normal;
  font-size: 14px;
  line-height: 16px;
}

.van-field__button {
  color: #ef7907;
  background: #f5f5f5;
  padding: 0 4px;
  margin-left: 10px;
  font-weight: bold;
}

.van-cell.required::before {
  content: '*';
  color: red;
  position: absolute;
  left: 1.6vw;
  top: 3.1vw;
}

.van-field__control--right {
  margin-right: 10px;
}

.van-dialog__confirm,
.van-dialog__confirm:active {
  color: #5D5DEF;
}

::v-deep .van-uploader__preview-image {
  width: 72px;
  height: 72px;
}


// 新增   2024年7月24日13:59:00 
.setDiningTitle {
  padding: 10px 16px 8px 10px;
  font-size: 14px;
  font-weight: bold;
}

.diningTitle {
  margin: 0;
  padding: 10px 16px 6px;
  font-weight: normal;
  font-size: 14px;
  line-height: 16px;
  .date{
    color: #004386;
  }
  .status{
    color:#949b9e // rgba(69, 90, 100, 0.6);
  }
}

.van-cell__title .diningTitle{
  padding: 10px 0px 6px;
}

// ::v-deep .van-tab {
//     -webkit-box-pack: start;
//     -ms-flex-pack: start;
//     justify-content: flex-start;
// }

.confirmInfo {
  .diningTag {
    margin-right: 5px;

    .red {
      color: #f30
    }
    .green {
      color: #24bfa0
    }
  }
  .van-cell__title {
    flex-direction: column;
  }
}
.confirmBtn {
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-shrink: 0;
  flex-shrink: 0;
  padding: 8px 16px;

  .van-button:first-of-type {
    border-top-left-radius: 20px;
    border-bottom-left-radius: 20px;
    width: 150%;
  }

  .van-button:last-of-type {
    border-top-right-radius: 20px;
    border-bottom-right-radius: 20px;
    width: 60%;
  }
}

.noData {
  background: #fff7ef;
    padding: 6px 17px;
    font-size: 14px;
    color: #cd7521;
    line-height: 31px;
}
.diningWrap{
  box-shadow: 0px 3px 5px 0px #edecec;
    margin-bottom: 2vw;
}
</style>